<template>
  <el-dialog
    @close="cancel"
    :title="title"
    :visible.sync="open"
    width="600px"
    class="dialogClass"
    append-to-body
  >
    <template slot="title">
      <div class="modalTitle">
        <img
          src="../../../../assets/bluelogo/drawerTitle.png"
          alt=""
          class="titleLogo"
        />{{ title }}
      </div>
    </template>

    <div>
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        size="small"
        label-width="100px"
      >
        <el-form-item label="申请单位:" prop="deptName" collapse-tags>
          <el-input
            v-model="formData.deptName"
            placeholder="请输入申请单位"
            :maxlength="1000"
            clearable
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="协同案件:" prop="caseIds">
          <el-select v-model="formData.caseIds" multiple collapse-tags>
            <el-option
              v-for="item in caseOptions"
              :key="item.id"
              :label="item.caseName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="协同任务:" prop="taskIds">
          <el-select v-model="formData.taskIds" multiple collapse-tags>
            <el-option
              v-for="item in tasks"
              :key="item.id"
              :label="item.taskName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请事由:" prop="applyReason">
          <el-input
            v-model="formData.applyReason"
            type="textarea"
            placeholder="请输入申请事由"
            :maxlength="300"
            show-word-limit
            :autosize="{ minRows: 7 }"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <div class="dialog-footer">
        <el-button @click="cancel" class="resetButton">取消</el-button>
        <el-button class="searchButton" @click="submitForm">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import {
  addColl,
  getInfo,
  updateColl,
  listTask,
} from "@/api/collaboration/collaboration.js";

import { getCaseByTask, getCaseList } from "@/api/caseManage/case";
export default {
  inheritAttrs: false,
  props: ["modalType", "id", "caseOptions", "taskOptions"],
  data() {
    // 协同任务校验
    // var checkkong = (rule, value, callback) => {
    //   if (!value) {
    //     callback(new Error("请选择协同任务"));
    //   } else {
    //     callback();
    //   }
    // };
    // 协同案件校验
    var checkkong1 = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error("请选择协同案件"));
      } else {
        this.tasks=[];
        //根据案件拿任务
        value.forEach((caseId) => {
          let taskList = this.taskOptions.filter((item) => {
            return item.caseId == caseId;
          });
          taskList.forEach((item) => {
            this.tasks.push(item);
          });
        });
        // console.log('this.tasks :>> ', this.tasks);
        callback();
      }
    };
    return {
      isDisabled: false,
      //案件下拉框禁用
      disabled: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 协同任务下拉框
      tasks: [],
      //标志位，解决页面进来就由于请求后端caseIds改变触发watch清空taskId[]列表问题
      flag:false,
      // 表单绑定数据
      formData: {
        //申请人id
        applicantId: this.$store.state.user.userId,
        // taskId: null,
        // caseId: null,
        taskIds: [],
        caseIds: [],
        caseName: "",
        applyReason: "",
      },
      // 校验
      rules: {
        // 协同任务的校验
        // taskId: [
        //   {
        //     required: true,
        //     validator: checkkong,
        //     trigger: "change",
        //   },
        // ],

        // 协同案件的校验
        caseIds: [
          {
            required: true,
            validator: checkkong1,
            trigger: "change",
          },
        ],
        // 申请事由的校验
        applyReason: [
          {
            required: true,
            message: "请写申请事由",
            trigger: "blur",
          },
        ],
      },
    };
  },
  watch: {
    "formData.caseIds":{
      deep:true,
      handler(value){
        if(this.flag){
          console.log('this.formData.taskIds:>> ', this.formData.taskIds);
        this.formData.taskIds.splice(0,this.formData.taskIds.length);
        }
      }
    },
    modalType: {
      handler(value) {
        if (value == "add") {
          this.open = true;
          this.title = "新增";
          // 拿到申请单位
          this.formData.deptName = this.$store.state.user.dept.deptName;
        } else if (value == "edit") {
          this.open = true;
          this.title = "修改";
          if (this.id) {
            getInfo(this.id).then((response) => {
              this.formData = response.data;
              //根据案件拿任务
              this.formData.caseIds?.forEach((caseid) => {
                let taskList = this.taskOptions.filter((item) => {
                  return item.caseId == caseid;
                });
                taskList.forEach((item) => {
                  this.tasks.push(item);
                });
              });
            setTimeout(() => {
              this.flag=true;
            },500)
            });
          }
        }
      },
      immediate: true,
    },
    //根据任务拿案件
    // "formData.taskId": {
    //   deep: true,
    //   handler(value) {
    //     console.log('value :>> ', value);
    //     if (value != "" && value != null) {
    //       getCaseByTask(value).then((res) => {
    //         this.formData.caseName = res.data.caseName;
    //         this.formData.caseId = res.data.id;
    //       });
    //     }
    //   },
    // },
  },

  methods: {
    // 取消按钮
    cancel() {
      this.$emit("update:modalType", "");
      this.open = false;
      this.tasks = [];
      this.flag=false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.formData = {
        applicantId: this.$store.state.user.userId,
        taskIds: [],
        caseIds: [],
        caseName: "",
        applyReason: "",
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.modalType == "edit") {
            this.formData.id = this.id;
            updateColl(this.formData)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.tasks = [];
                this.flag=false;
                this.$emit("update:modalType", "");
                this.$emit("fatherMethod");
              })
              .catch(() => {
                this.$modal.msgError("修改失败");
              });
          } else if (this.modalType == "add") {
            addColl(this.formData)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.tasks = [];
                this.$emit("update:modalType", "");
                this.$emit("fatherMethod");
              })
              .catch(() => {
                this.$modal.msgError("新增失败");
              });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../../assets/styles/dialog.scss"; //模态框样式

::v-deep .label {
  font-size: 14px !important;
  font-family: Microsoft YaHei !important;
  font-weight: 400 !important;
  // color: #598af9 !important;
  margin-top: 15px;
}
::v-deep .content {
  font-size: 14px;
  margin-left: 30px;
  margin-top: 15px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #aeafb0;
}
::v-deep .el-descriptions-item__container {
  margin-bottom: 15px;
}
::v-deep.el-select {
  width: 100%;
}
::v-deep.el-form-item {
  margin-left: -10px !important;
}
.dialogClass{
 ::v-deep .el-dialog{
  top: 80px;
  }
}
</style>
